package cn.b.sky.user.controller;

import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@RequestMapping("/common/*")
@Controller
public class CommonController extends SecurityController {
  @Resource
  private AttachmentService attachmentService;
  
  @RequestMapping(value = "showReport")
  public String showReport(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "common/batchjobReport";
  }

  @RequestMapping("downloadAttachement")
  public void downloadAttachement(HttpServletResponse response, String fileName, String attachmentCode)
      throws IOException {
    if (!StringUtils.isBlank(attachmentCode)) {
      Attachment attachment = attachmentService.selectAttachmentByAttachmentCode(this.getSiteCode(), attachmentCode);
      if (attachment != null && !StringUtils.isBlank(attachment.getSavePath())) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");

        OutputStream os = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;fileName="
            + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        ftpUtils.fileDownload(attachment.getSavePath(), os);
        os.flush();
        os.close();
      } else {
        throw ImeException.newException("attachment.C,doesNotExist.C");
      }

    }
  }

  @RequestMapping("showAttachement")
  public void showAttachement(HttpServletResponse response, String attachmentCode) throws IOException {
    if (!StringUtils.isBlank(attachmentCode)) {
      Attachment attachment = attachmentService.selectAttachmentByAttachmentCode(this.getSiteCode(), attachmentCode);
      if (attachment != null && !StringUtils.isBlank(attachment.getSavePath())) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");

        OutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        ftpUtils.fileDownload(attachment.getSavePath(), os);
        os.flush();
        os.close();
      } else {
        throw ImeException.newException("picture.C,doesNotExist.C");
      }

    }
  }
}
